// task_transaction_record_viewmodel.dart
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:sjx/pages/mine/transaction/task_transaction_record_page.dart';

import '../../../repository/model/task_transaction_record_model.dart';
import '../../../repository/sjx_api.dart';

class TaskTransactionRecordViewModel extends ChangeNotifier {
  final TaskRecordType type;
  final int category;

  TaskTransactionRecordViewModel({
    required this.type,
    required this.category,
  });

  // 状态变量
  final List<String> _monthList = [];
  final Map<String, List<TaskTransactionRecordModel>> _monthDataMap = {};
  int _pageNum = 1;
  final int _pageSize = 20;
  String? _selectedYearMonth;
  String? _selectedYearMonthStr;

  bool _isLoading = false;
  bool _isRefreshing = false;
  bool _isLoadingMore = false;
  bool _hasError = false;
  String _errorMessage = '';
  bool _hasNoMoreData = false;

  // Getter 方法
  List<String> get monthList => _monthList;
  Map<String, List<TaskTransactionRecordModel>> get monthDataMap => _monthDataMap;
  bool get isLoading => _isLoading;
  bool get isRefreshing => _isRefreshing;
  bool get isLoadingMore => _isLoadingMore;
  bool get hasError => _hasError;
  String get errorMessage => _errorMessage;
  bool get hasNoMoreData => _hasNoMoreData;
  String? get selectedYearMonthStr => _selectedYearMonthStr;

  // 加载数据
  Future<void> loadData({bool isRefresh = false, bool isLoadMore = false}) async {
    if (_isLoading) return;

    _setLoadingState(isRefresh: isRefresh, isLoadMore: isLoadMore);

    try {
      final response = await _fetchRecordData();

      _processResponseData(response, isRefresh: isRefresh);

      _handleSuccess(isRefresh: isRefresh);
    } catch (e) {
      _handleError(e, isRefresh: isRefresh, isLoadMore: isLoadMore);
    }
  }

  // 下拉刷新
  Future<void> refresh() async {
    _pageNum = 1;
    _hasNoMoreData = false;
    await loadData(isRefresh: true);
  }

  // 上拉加载更多
  Future<void> loadMore() async {
    if (_hasNoMoreData || _isLoadingMore) return;
    _pageNum++;
    await loadData(isLoadMore: true);
  }

  // 设置加载状态
  void _setLoadingState({bool isRefresh = false, bool isLoadMore = false}) {
    _isLoading = true;
    _hasError = false;

    if (isRefresh) {
      _isRefreshing = true;
    } else if (isLoadMore) {
      _isLoadingMore = true;
    }

    notifyListeners();
  }

  // 处理成功响应
  void _handleSuccess({bool isRefresh = false}) {
    _isLoading = false;
    _isRefreshing = false;
    _isLoadingMore = false;
    notifyListeners();
  }

  // 处理错误
  void _handleError(dynamic error, {bool isRefresh = false, bool isLoadMore = false}) {
    _isLoading = false;
    _isRefreshing = false;
    _isLoadingMore = false;
    _hasError = true;
    _errorMessage = error.toString();

    // 如果是加载更多失败，回退页码
    if (isLoadMore) {
      _pageNum--;
    }

    notifyListeners();
  }

  // 获取记录数据
  Future<List> _fetchRecordData() async {
    final Map<String, dynamic> params = {
      'page': _pageNum,
      'size': _pageSize,
      'exchangeType': category == 0 ? '收入' : '支出',
      if (_selectedYearMonth != null) 'endDate': _selectedYearMonth,
    };
    if (type == TaskRecordType.coin) {
      Response response = await SJXApi.instance().userExchangesCoin(params);
      return response.data['coinExchangeDtos'];
    } else if (type == TaskRecordType.cash) {
      Response response = await SJXApi.instance().userExchanges(params);
      return response.data['userExchangeInfos'];
    } else {
      return [];
    }
  }

  // 处理响应数据
  void _processResponseData(List dataList, {bool isRefresh = false}) {
    if (isRefresh) {
      _monthList.clear();
      _monthDataMap.clear();
    }

    for (var item in dataList) {
      final record = TaskTransactionRecordModel.fromJson(item);
      final month = record.month;
      if (month != null) {
        if (!_monthDataMap.containsKey(month)) {
          _monthList.add(month);
          _monthDataMap[month] = [];
        }
        _monthDataMap[month]!.add(record);
      }
    }

    // 检查是否还有更多数据
    if (dataList.length < _pageSize) {
      _hasNoMoreData = true;
    }
  }

  // 选择时间
  void selectTime(DateTime selectedDate) {
    _selectedYearMonthStr =
    '${selectedDate.year}年${selectedDate.month.toString().padLeft(2, '0')}月';
    _selectedYearMonth =
    '${selectedDate.year}-${selectedDate.month.toString().padLeft(2, '0')}-31';
    notifyListeners();
    refresh();
  }

  // 清除错误状态
  void clearError() {
    _hasError = false;
    _errorMessage = '';
    notifyListeners();
  }

  // 模拟金币数据
  List<Map<String, dynamic>> _getMockCoinData() {
    if (_pageNum > 2) return []; // 模拟没有更多数据

    return [
      {
        'amount': '+100',
        'createTime': '2024-01-15 10:30:00',
        'description': '任务奖励',
        'month': '2024年01月',
        'statusDescription': '已完成',
      },
      {
        'amount': '+50',
        'createTime': '2024-01-14 14:20:00',
        'description': '签到奖励',
        'month': '2024年01月',
        'statusDescription': '',
      },
    ];
  }

  // 模拟现金数据
  List<Map<String, dynamic>> _getMockCashData() {
    if (_pageNum > 2) return []; // 模拟没有更多数据

    return [
      {
        'amount': '+12.00',
        'exchangeDay': '2024年01月15日',
        'description': '邀请奖励',
        'month': '2024年01月',
        'statusDescription': '已到账',
      },
      {
        'amount': '+8.00',
        'exchangeDay': '2024-01-14',
        'description': '任务完成',
        'month': '2024年01月',
        'statusDescription': '',
      },
    ];
  }
}